package com.yuandian.management.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

/**
 *  <p>
 *  Jackson工具类
 *  <p>
 * @author VaeTang
 * @date 2020/06/09
 * @since 1.0.0
 */
public class JacksonUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    private JacksonUtil(){}

    /**
     * json字符串转对象
     * @param body
     * @param field
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseObject(String body, String field, Class<T> clazz) {
        JsonNode node = null;
        try {
            node = mapper.readTree(body);
            node = node.get(field);
            return mapper.treeToValue(node, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * json字符串转map
     * @param data
     * @return
     */
    public static Map<String, String> toMap(String data) {
        try {
            return mapper.readValue(data, new TypeReference<Map<String, String>>(){});
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对象转json字符串
     *
     * @param obj 带转换obj
     * @return
     */
    public static String objectToString(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }
}
